package r929.servletJsonpFilter;

import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ServletJsonpFilter implements Filter {
	
	private static String JSON_MIME_TYPE	=	"application/json";
	private static String JAVASCRIPT_MIME_TYPE	=	"application/javascript";
	
	private static final Logger logger = Logger.getLogger(ServletJsonpFilter.class);
	
	@Override
	public void init(FilterConfig config) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		String callback	=	request.getParameter("callback");
		String callbackId	=	request.getParameter("callbackId");
		if(callback != null){
			logger.info("callback != null");
			JsonpResponseWrapper jsonpResponseWrapper	=	new JsonpResponseWrapper((HttpServletResponse) response);
			chain.doFilter(request, jsonpResponseWrapper);
			
			logger.info("MIME Type : "+jsonpResponseWrapper.getContentType().toLowerCase());
			if(jsonpResponseWrapper.getContentType().toLowerCase().indexOf(JSON_MIME_TYPE) >= 0){
				jsonpResponseWrapper.setContentType(JAVASCRIPT_MIME_TYPE);
				StringBuilder jsonpResult	=	new StringBuilder();
				jsonpResult.append(callback);
				jsonpResult.append("(");
				jsonpResult.append(jsonpResponseWrapper.getJsonResult());
				if(callbackId != null){
					logger.info("callbackId != null");
					jsonpResult.append(",\"");
					jsonpResult.append(callbackId);
					jsonpResult.append("\"");
				}
				jsonpResult.append(");");
				try{
					response.getWriter().print(jsonpResult.toString());
				}catch(IllegalStateException ex){
					OutputStreamWriter out	=	new OutputStreamWriter(response.getOutputStream(), jsonpResponseWrapper.getCharacterEncoding());
					out.write(jsonpResult.toString());
					out.flush();
					out.close();
				}
				response.flushBuffer();
				
			}else{
				jsonpResponseWrapper.flushBufferToResponse();
			}
		}else{
			logger.info("callback == null");
			chain.doFilter(request, response);
		}
	}
	
	@Override
	public void destroy() {

	}
	
}
